package com.panyunting.notepad.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.panyunting.notepad.R;
import com.panyunting.notepad.database.NotepadDao;


import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class RecordActivity extends AppCompatActivity implements View.OnClickListener {
    private ImageView btnback,btnsaveRecord;
    private EditText etContent;
    private TextView tvTitle,tvRecordTime;
    private String id;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_record);
        btnback = findViewById(R.id.back);
        btnsaveRecord = findViewById(R.id.saveNote);
        etContent = findViewById(R.id.et_content);
        tvTitle = findViewById(R.id.tv_title);
        tvRecordTime = findViewById(R.id.tv_record_time);
        btnback.setOnClickListener(this);
        btnsaveRecord.setOnClickListener(this);
        Intent intent = getIntent();
        //判断是否是点击某个条目传过来，此时intent中有数据
        if (intent != null) {
            String content = intent.getStringExtra("content");
            String noteTime = intent.getStringExtra("noteTime");
            tvTitle.setText("记事本详情");
            etContent.setText(content);
            tvRecordTime.setText(noteTime);
            tvRecordTime.setVisibility(View.VISIBLE);

        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                //关闭当前页面
                this.finish();
                break;
            case R.id.saveNote://这里即可能是添加数据也可能是修改数据
                //3先判断id值，如果id不为空，则是修改
                savenote();
                break;
        }
    }
    void savenote () {
        String content = etContent.getText().toString().trim();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        //获得今天的日期时间
        Date date = new Date(System.currentTimeMillis());
        String time = simpleDateFormat.format(date);
        OkHttpClient client = new OkHttpClient();
        JSONObject formjson = new JSONObject();
        formjson.put("id", new Random().nextInt());
        formjson.put("username", getSharedPreferences("info",MODE_PRIVATE).getString("username",""));
        formjson.put("name", getSharedPreferences("info",MODE_PRIVATE).getString("username",""));
        formjson.put("create_time", time );
        formjson.put("content", content );
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType,  formjson.toJSONString());
        Request request = new Request.Builder()
                .url("http://122.51.116.159:8080/books/AddBookServlet")
                .post(body)
                .addHeader("content-type", "application/json")
                .addHeader("cache-control", "no-cache")
                .build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Toast.makeText(RecordActivity.this, "Post Failed", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String res = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.d("TAG", "run: " + res);
                        JSONObject jsonObject = JSONObject.parseObject(res);
                        if(jsonObject.getIntValue("code") == 1) {
                            setResult(2); //这句话目的就是为了能够回调NotePadActivity的onActivityResult方法
                            finish();//关闭当前页面
                        }
                    }
                });
            }
        });
    }
}
